'use strict';

const Controller = require('egg').Controller;

class ExperienceCommentController extends Controller {
  // 获取评论列表
  async index() {
    const { ctx } = this;
    const { experience_id } = ctx.query;
    
    try {
      if (!experience_id) {
        ctx.body = {
          code: 400,
          message: '经验ID不能为空',
          data: null,
        };
        return;
      }
      
      const comments = await ctx.service.experienceComment.findByExperienceId(experience_id);
      ctx.body = {
        code: 200,
        message: '获取评论列表成功',
        data: comments,
      };
    } catch (error) {
      ctx.logger.error('获取评论列表失败:', error);
      ctx.body = {
        code: 500,
        message: '获取评论列表失败',
        data: null,
      };
    }
  }

  // 创建评论
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    
    // 从JWT token中获取用户ID
    const userId = ctx.user?.id;
    if (!userId) {
      ctx.body = {
        code: 401,
        message: '未登录',
        data: null
      };
      return;
    }
    data.user_id = userId;
    
    try {
      const comment = await ctx.service.experienceComment.create(data);
      ctx.body = {
        code: 200,
        message: '发表评论成功',
        data: comment,
      };
    } catch (error) {
      ctx.logger.error('发表评论失败:', error);
      ctx.body = {
        code: 500,
        message: '发表评论失败',
        data: null,
      };
    }
  }
}

module.exports = ExperienceCommentController;
